<?php
namespace app\admin\controller;
use think\Controller;

class Home extends BaseAdmin{
    public function index(){
        $menus = false;
        $role = $this->db->table('admin_groups')->where(array('gid'=>$this->_admin['gid']))->item();//查询gid=$this->_admin['gid']的数据
        if($role){
            $role['rights'] = (isset($role['rights']) && $role['rights']) ? json_decode($role['rights'],true) : [];
            //判断用户是否拥有权限，如果存在则对rights的json数据进行解码为数组，不存在则返回空数组
        }
        if($role['rights']&&$this->_admin['gid'] == '1'){
            $where = array('ishidden'=>0,'status'=>0);//查询菜单id，隐藏菜单正常，状态正常的数据
            $menus = $this->db->table('admin_menus')->where($where)->order('ord', 'desc')->cates('mid');//自定义索引列表
            $menus && $menus = $this->gettreeitems($menus);
        }else{
            $where = 'mid in('.implode(',',$role['rights']).') and ishidden=0 and status=0';//查询菜单id，隐藏菜单正常，状态正常的数据
            $menus = $this->db->table('admin_menus')->where($where)->order('ord', 'desc')->cates('mid');//自定义索引列表
            $menus && $menus = $this->gettreeitems($menus);
        }

        //        if($this->_admin['gid'] == '0'){
//            $where = 'mid in('.implode(',',$role['rights']).') and ishidden=0 and status=0';//查询菜单id，隐藏菜单正常，状态正常的数据
//            $menus = $this->db->table('admin_menus')->where($where)->order('ord', 'desc')->cates('mid');//自定义索引列表
//            $menus && $menus = $this->gettreeitems($menus);
//        }
        $site = $this->db->table('admin_sites')->where(array('names'=>'site'))->item();
        $site && $site['values'] = json_decode($site['values']);
        $ip = array_key_exists('HTTP_X_FORWARDED_FOR',$_SERVER)?$_SERVER['HTTP_X_FORWARDED_FOR']:$_SERVER['REMOTE_ADDR'];
        $this->Tool->writeLog($ip,'ip');
        $this->assign('ip',$ip);
        $this->assign('site',$site);//标题
        $this->assign('role',$role);//权限
        $this->assign('menus',$menus);//菜单
        return $this->fetch();
    }
    private function gettreeitems($items){
        $tree = array();
        foreach ($items as $item) {//$itmes二维数组,$item为里面数组
            if(isset($items[$item['pid']])){//判断$item数组中的pid上级菜单是否设置并且非NULL
                $items[$item['pid']]['children'][] = &$items[$item['mid']];
            }elseif($item['pid']==0){
                $tree[] = &$items[$item['mid']];//pid为0执行该语句，设置一级菜单
            }
        }
        return $tree;
    }

    // 欢迎页面
    public function welcome(){
        return $this->fetch();
    }
}